package com.bookshop.interceptor;

import com.bookshop.annotation.RequirePerms;
import com.bookshop.aspect.exception.CustomException;
import com.bookshop.entity.Permission;
import com.bookshop.service.UserService;
import com.bookshop.util.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author g2l
 * @create 2024-01-15 19:55
 */
@Slf4j
@Component
public class PermissionInterceptor implements HandlerInterceptor{

    @Resource
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;

            // 获取指定注解
            RequirePerms perms = handlerMethod.getMethodAnnotation(RequirePerms.class);

            // 有注解才判断
            if (perms != null) {
                // 获取注解的值
                String value = perms.value();
                // 获取手机号
                String phoneNumber = (String) request.getAttribute("phoneNumber");
                // 为了提升处理效率，这里自己写sql查询
                List<Permission> permissions = userService.getPermissions(phoneNumber);
                for (Permission permission:permissions){
                    if (value.equals(permission.getOperation())){
                        return true;
                    }
                }
                throw new CustomException("权限不足");
            }
            // 没加权限注解，直接放行
        }
        return true;
    }
}
